import Verticalbar from "../charts/Verticalbar"
import ProgressBar from "../components/ProgressBar";
import axios from 'axios';
import React, { useRef, useEffect, useState, useMemo, useCallback } from 'react';
import analyticsData from "../charts/assets/analyticsData";
import { ScrollView, StyleSheet, Text, Button, View, TouchableOpacity, Dimensions, RefreshControl } from "react-native";
import BottomSheet, { BottomSheetScrollView, BottomSheetBackdrop } from "@gorhom/bottom-sheet";
import BoxCard from "../components/BoxCard";
import ZoomHorizontalbar from "../charts/ZoomHorizontalbar";
import TitleBox from "../components/TitleBox";
base = "http://192.168.43.57:8088/"

const options = {
    method: "POST",
    url: base + "analyze_area"
};

const { width, height } = Dimensions.get('window')

export default function Data() {
    // hooks
    const sheetRef = useRef(null);

    const [areaname, setareaname] = useState('渝北');
    const [Countyname, setCountyname] = useState('中央公园');
    const [decoration_new, setdecoration_new] = useState(null);
    const [orientation_new, setorientation_new] = useState(null);
    const [house_type_new, sethouse_type_new] = useState(null);
    const [area_avg_price_data, setarea_avg_price_data] = useState(null);
    const [spinning, setSpinning] = useState(false);
    const snapPoints = useMemo(() => ["25%", "50%", "90%"], []);
    // 定义区县列表
    const AreaList = useMemo(
        () =>
            findAreaByLabel(analyticsData.city_area_community, areaname).children
                .map((item, index) => `${item.value}`),
        [areaname]
    );
    // 定义区域列表
    const CountryList = useMemo(
        () =>
            findAreaByLabel(findAreaByLabel(analyticsData.city_area_community, areaname)['children'], Countyname)['children']
                .map((item, index) => `${item.value}`),
        [areaname, Countyname]
    );

    // 页面初始加载
    useEffect(() => {
        setarea_avg_price_data(analyticsData.area_avg_price_data_new)
    }, []);

    // 左侧选择区域
    function SelectArea(name) {
        console.log('父组件Log：', name)
        OpenBottomSheet()
        console.log(typeof analyticsData.city_area_community)
        console.log('被选中内容:', findAreaByLabel(analyticsData.city_area_community, name).children[0]['value'])
        setareaname(name)
        setCountyname(findAreaByLabel(analyticsData.city_area_community, name).children[0]['value'])
    }
    // 处理数组及children
    function findAreaByLabel(area, area_name) {
        return area.find(function (element) {
            return element.label === area_name;
        });
    }
    // 弹出BottomSheet
    const OpenBottomSheet = () => {
        handleSnapPress(0)
    }
    // 关闭BottomSheet
    const CloaseBottomSheet = () => {
        handleClosePress()
    }
    // 加载详细信息
    function GetDetailData(data) {
        console.log('data:', data)
        setSpinning(true);
        Object.assign(options, data)
        console.log('options:', options)
        axios.request(options).then((response) => {
            console.log(response.data)
            console.log('朝向分布:', response.data.data.orientation_new_list)
            setorientation_new(response.data.data.orientation_new_list)
            setdecoration_new(response.data.data.decoration_new_list)
            sethouse_type_new(response.data.data.house_type_new_list)
            setSpinning(false);
            if (response.status == 200) {
                CloaseBottomSheet()
            }
        });
    }

    // 处理BottomSheet动作的回调
    const handleSheetChange = useCallback((index) => {
        console.log("handleSheetChange", index);
    }, []);
    const handleSnapPress = useCallback((index) => {
        sheetRef.current?.snapToIndex(index);
    }, []);
    const handleClosePress = useCallback(() => {
        sheetRef.current?.close();
    }, []);

    // 区域render
    const renderItem = (item) => (
        <TouchableOpacity onPress={() => { console.log('Item clicked:', item), setCountyname(item) }} key={item} style={styles.itemContainer}>
            <Text>{item}</Text>
        </TouchableOpacity>
    );
    // 小区render
    const renderCountryItem = (item) => {
        const { code } = item;
        return (
            <TouchableOpacity onPress={() => { console.log('Item clicked:', item); GetDetailData({ data: { city: areaname, area: Countyname }, headers: { "content-type": "application/x-www-form-urlencoded" }, }) }} key={'Country' + item + Math.random(0, 10)} style={styles.itemContainer}>
                <Text>{item}</Text>
            </TouchableOpacity>
        );
    };
    // 背景板render
    const renderBackdrop = useCallback(
        props => (
            <BottomSheetBackdrop
                {...props}
                disappearsOnIndex={0}
                appearsOnIndex={2}
            />
        ),
        []
    );
    return (
        <>
            <ScrollView
                style={
                    styles.container
                }
                refreshControl={
                    <RefreshControl
                        refreshing={spinning}
                        colors={['#887ef2']} // 设置colors属性（Android）
                        tintColor="#887ef2" // 设置tintColor属性（iOS）
                    />
                }
            >
                {area_avg_price_data ? (
                    <BoxCard>
                        <TitleBox title="区县-平均价格" label="重庆市各区县平均价格排名"></TitleBox>
                        <ZoomHorizontalbar series={area_avg_price_data.series} labels={area_avg_price_data.labels} onPress={(params) => SelectArea(params)}></ZoomHorizontalbar>
                    </BoxCard>
                ) : (
                    <></>
                )}
                {orientation_new ? (
                    <BoxCard>
                        <TitleBox title="房屋朝向分布" label={`该项数据统计${areaname}所有房源的朝向占比`}></TitleBox>
                        {
                            orientation_new.data.map((item, index) => <ProgressBar key={index} title={item.labels} value={item.series} percent={item.percent}></ProgressBar>)
                        }
                    </BoxCard>
                ) : (
                    <></>
                )}
                {decoration_new ? (
                    <BoxCard>
                        <TitleBox title="装修情况分布" label={`该项数据统计${areaname}所有房源的装修情况占比`}></TitleBox>
                        {
                            decoration_new.data.map((item, index) => <ProgressBar key={index} title={item.labels} value={item.series} percent={item.percent}></ProgressBar>)
                        }
                    </BoxCard>
                ) : (
                    <></>
                )}
                {house_type_new ? (
                    <BoxCard>
                        <TitleBox title="房屋户型分布" label={`该项数据统计${areaname}所有房源的房屋户型占比`}></TitleBox>
                        {
                            house_type_new.data.map((item, index) => <ProgressBar key={index} title={item.labels} value={item.series} percent={item.percent}></ProgressBar>)
                        }
                    </BoxCard>
                ) : (
                    <></>
                )}
            </ScrollView>
            {/* 弹出层 */}
            <BottomSheet
                ref={sheetRef}
                index={1}
                snapPoints={snapPoints}
                onChange={handleSheetChange}
                enablePanDownToClose={true}
                backdropComponent={renderBackdrop}
                handleIndicatorStyle={{ backgroundColor: '#887ef2' }}
            >
                <BottomSheetScrollView contentContainerStyle={styles.contentContainer}>
                    <ScrollView
                        style={{
                            width: '50%',
                            flex: 1
                        }}
                    >
                        {AreaList.map(renderItem)}
                    </ScrollView>
                    {/* <View style={{ width: 1, backgroundColor: '#000000', flex: 1, left: '50%' }}>

                    </View> */}
                    <ScrollView
                        style={{
                            width: '50%',
                            flex: 1
                        }}
                    >
                        {CountryList.map((item) => renderCountryItem(item))}
                    </ScrollView>
                </BottomSheetScrollView>
            </BottomSheet>
        </>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        // padding: 17
    },
    contentContainer: {
        backgroundColor: "white",
        position: 'relative',
        display: 'flex',
        flexDirection: 'row'
    },
    itemContainer: {
        padding: 6,
        margin: 6,
        backgroundColor: '#e7e5fc',
        borderRadius: 5
    },
})